package com.behome.web.controller.media;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.behome.common.annotation.Log;
import com.behome.common.core.controller.BaseController;
import com.behome.common.core.domain.AjaxResult;
import com.behome.common.core.page.TableDataInfo;
import com.behome.common.enums.BusinessType;
import com.behome.common.enums.FileTypeEnum;
import com.behome.common.utils.DictUtils;
import com.behome.common.utils.file.FileUtils;
import com.behome.common.utils.file.VideoUtil;
import com.behome.system.domain.TMediaSource;
import com.behome.system.service.IMediaSourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 媒资库
 *
 * @author behome
 */
@RestController
@Api(tags = "媒资库")
@RequestMapping("/media/mediaSource")
public class MediaSourceController extends BaseController {
    @Resource
    private IMediaSourceService mediaSourceService;
    @Value("${behome.mediaPath}")
    private String mediaPath;

    /**
     * 获取媒资分类列表
     */
    @PreAuthorize("@ss.hasPermi('media:mediaSource:list')")
    @ApiOperation("获取媒资列表")
    @GetMapping("/list")
    public TableDataInfo list(TMediaSource mediaSource) {
        startPage();
        mediaSource.setUploadUser(getUserId());
        mediaSource.setRegionId(getRegionId());
        List<TMediaSource> list = mediaSourceService.selectMediaSourceList(mediaSource);
        return getDataTable(list);
    }


    /**
     * 新增媒资信息
     */
    @PreAuthorize("@ss.hasPermi('media:mediaSource:add')")
    @Log(title = "媒资管理", businessType = BusinessType.INSERT)
    @ApiOperation("新增媒资信息")
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TMediaSource mediaSource) {
        mediaSource.setRegionId(getRegionId());
        mediaSource.setUploadTime(new Date());
        mediaSource.setUploadUser(getUserId());
        mediaSource.setReviewStatus(0);
        return toAjax(mediaSourceService.insert(mediaSource));
    }

    /**
     * 修改媒资信息
     */
    @PreAuthorize("@ss.hasPermi('media:mediaSource:edit')")
    @Log(title = "媒资管理", businessType = BusinessType.UPDATE)
    @ApiOperation("修改媒资信息")
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TMediaSource mediaSource) {
        if (mediaSourceService.checkMediaNameUnique(mediaSource)) {
            return error("修改媒资'" + mediaSource.getMediaName() + "'失败，该媒资名称已存在");
        }
        return toAjax(mediaSourceService.update(mediaSource));
    }

    /**
     * 删除媒资信息
     */
    @PreAuthorize("@ss.hasPermi('media:mediaSource:remove')")
    @Log(title = "媒资管理", businessType = BusinessType.DELETE)
    @ApiOperation("删除媒资信息")
    @DeleteMapping("/{Ids}")
    public AjaxResult remove(@PathVariable Long[] Ids) {
        return toAjax(mediaSourceService.deleteMediaTypeIds(Ids));
    }

    @Log(title = "音频上传", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('media:mediaSource:uploadFile')")
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file) {
        HashMap<String, Object> map = new HashMap<>();
        String[] split = Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
        String suffix = split[split.length - 1];
        String newFileName = IdUtil.simpleUUID() + "." + suffix;
        File upgradeFile = new File(mediaPath + File.separator + newFileName);
        try {
            InputStream inputStream = file.getInputStream();
            OutputStream os = Files.newOutputStream(upgradeFile.toPath());
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
            map.put("fileSize", FileUtils.readableFileSize(upgradeFile));
            map.put("timeLength", VideoUtil.getDuration(upgradeFile));
            map.put("fileName", newFileName);
            map.put("filePath", upgradeFile.getAbsolutePath());
            String upperCase = FileTypeEnum.getValue(suffix.toUpperCase());
            String tMediaFileType = DictUtils.getDictValue("t_media_file_type", upperCase);
            map.put("fileType", Integer.valueOf(tMediaFileType));
            return AjaxResult.success("上传成功", map);
        } catch (Exception e) {
            return AjaxResult.error("上传失败");
        }
    }

    @PostMapping("/deleteFile")
    public AjaxResult deleteFile(@RequestBody TMediaSource mediaSource) {
        File upgradeFile = new File(mediaSource.getFilePath());
        try {
            if (upgradeFile.exists()) {
                FileUtil.del(upgradeFile);
            }
            return AjaxResult.success("删除文件成功!");
        } catch (Exception e) {
            return AjaxResult.error("上传失败");
        }
    }

    @Log(title = "媒资管理", businessType = BusinessType.OTHER)
    @ApiOperation("文转语")
    @PostMapping(value = "/tts")
    public AjaxResult tts(@RequestBody TMediaSource mediaSource) {
        return mediaSourceService.tts(mediaSource);
    }

}
